package com.example.springDemo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

@Deprecated//表示已废弃
//@Configuration//表示它是一个配置类
public class MyDataSourceConfig {

    @ConfigurationProperties("spring.datasource")//与配置文件spring.datasource绑定
    @Bean//默认是没有数据源才配置默认的HikariDataSource(Hikari数据源)
    public DataSource MyDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        try {
            /**
             * stat:开启监控
             * wall:开启防火墙
             */
            druidDataSource.setFilters("stat,wall");//开启druid的数据库监控功能
            druidDataSource.setMaxActive(10);//最大的连接线程
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return druidDataSource;
    }

    /**
     * 配置druid 的监控页面
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        StatViewServlet servlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(servlet, "/druid/*");

        bean.addInitParameter("loginUsername","admin");//配置监控页面的账号密码
        bean.addInitParameter("loginPassword","123456");



        return bean;
    }

    /**
     * WebsterFilter用于采失web-jdbc关联监控的数据。
     */
    @Bean
    public FilterRegistrationBean webStatFilter(){
        WebStatFilter webStatFilter = new WebStatFilter();

        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));//拦截路径
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}
